package com.broada.apm.logic.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.base.BaseLogic;
import com.broada.apm.entity.Authenticate;
import com.broada.apm.logic.AuthenticationLogic;
import com.broada.apm.model.User;
import com.broada.apm.util.MD5Util;
import com.broada.apm.util.TokenManager;

public class AuthenticationLogicImpl  extends BaseLogic implements AuthenticationLogic{

	private static Logger log = LoggerFactory.getLogger(AuthenticationLogicImpl.class);
	
	@Override
	public Authenticate login(User user) throws Exception {
		String account = user.getAccount();
		Authenticate authenticate = new Authenticate();
		try {
			User _user = userService.getUserByAccount(account);
			if (_user == null || !MD5Util.string2MD5(user.getPassword()).equals(_user.getPassword())) {
				authenticate.setMessage("帐号不存在或密码错误");
			} else if (_user.getStatus() == 1) {
				authenticate.setMessage("帐号处于禁用状态,请联系系统管理员");
			} else {
				authenticate.setToken(TokenManager.generateToken(_user));
				authenticate.setUser(_user);
				authenticate.setStatus(true);
			}
		} catch (Exception e) {
			log.error("用户登录出错:{}", e);
		}
		return authenticate;
	}

	@Override
	public void logout(String token) throws Exception {
		TokenManager.invalidate(token);
	}

}
